/*
 * JSAction.java
 *
 * Created on September 24, 2003, 1:59 PM
 */

package abdn.graph.ontobrowser;

/**
 *
 * @author  skrivov
 */
import java.awt.event.ActionEvent;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JMenuItem;

public class JSAction {
  public static String processMacros(String name, OBNode node) {
    if (node instanceof OBRelationNode) {
      return null;
    }
    String out;
    try {
      URI uri = new URI(node.getID());
      out = name.replaceAll("NODE_ID", uri.getFragment().toString());
      out = out.replaceAll("NODE_LABEL", node.getLabel());
      return out;
    }
    catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }

  String ID;
  String description;
  Vector pars;
  public static ESDOntoBrowser esdOntoBrowser;
  /** Creates a new instance of JSAction */
  public JSAction(String _ID, String descr) {
    ID = _ID;
    description = descr;
    pars = new Vector();

  }

  public void addParameter(String p) {
    pars.addElement(p);
  }

  public String createJSFunction(OBNode node) {
    String func = ID + "('";
    if (!pars.isEmpty()) {
      int i;
      String par;
      for (i = 0; i < pars.size() - 1; i++) {
        par = processMacros( (String) pars.elementAt(i), node);

        func = func + par + "', '";
      }
      par = processMacros( (String) pars.elementAt(i), node);
      func = func + par;
    }
    func = func + "')";

    return func;
  }

  public JMenuItem createMenuItem(OBNode node) {
    TemplateAction ta =
        new TemplateAction(
        processMacros(description, node),
        createJSFunction(node));
    JMenuItem mi = new JMenuItem();
    mi.setAction(ta);
    return mi;
  }

  public class TemplateAction
      extends AbstractAction {
    String function;
    public TemplateAction(String name, String func) {
      super(name, null);
      // putValue(SHORT_DESCRIPTION, desc);
      function = func;

    }

    public void actionPerformed(ActionEvent e) {
      if (esdOntoBrowser.rtPolicy instanceof RTPolicyJS) {
        ( (RTPolicyJS) esdOntoBrowser.rtPolicy).call(function);
      }
    }
  }

}
